# coding=utf-8
# python version >= 3.6
import json
from alibabacloud_green20220302.client import Client
from alibabacloud_green20220302 import models
from alibabacloud_tea_openapi.models import Config
from alibabacloud_tea_util.models import RuntimeOptions
from setting import ALIYUN_ACCESS_KEY_ID, ALIYUN_ACCESS_KEY_SECRET



def create_green_client():
    """创建阿里云内容安全客户端"""
    config = Config(
        access_key_id=ALIYUN_ACCESS_KEY_ID,
        access_key_secret=ALIYUN_ACCESS_KEY_SECRET,
        connect_timeout=10000,  # 连接超时时间 单位毫秒(ms)
        read_timeout=10000,     # 读超时时间 单位毫秒(ms) - 增加超时时间
        region_id='cn-hangzhou',
        endpoint='green-cip.cn-hangzhou.aliyuncs.com'
    )
    return Client(config)

def text_moderation(content, service='comment_detection_pro'):
    """文本内容审核"""
    service_parameters = {'content': content}
    
    request = models.TextModerationPlusRequest(
        service=service,
        service_parameters=json.dumps(service_parameters)
    )
    
    client = create_green_client()
    runtime = RuntimeOptions(read_timeout=10000, connect_timeout=10000)
    
    try:
        response = client.text_moderation_plus_with_options(request, runtime)
        if response.status_code == 200:
            return response.body
        else:
            logger.error(f'API响应失败，状态码: {response.status_code}, 响应内容: {response}')
            return None
    except Exception as err:
        logger.error(f'文本审核请求异常: {err}')
        raise

def normalize_response(api_response):
    """
    将阿里云内容安全API响应转换为标准化的文本检测结果
    
    参数:
        api_response: 文本检测API返回的原始响应
        
    返回:
        标准化的结果字典
    """
    # 映射风险等级到建议
    risk_to_suggestion = {
        'none': 'pass',
        'low': 'review',
        'medium': 'review',
        'high': 'block',
        'review': 'review',
        'block': 'block'
    }
    
    # 确保api_response是字典格式
    if hasattr(api_response, 'to_map'):
        response_dict = api_response.to_map()
    else:
        response_dict = api_response
    
    # 提取Data部分
    data = response_dict.get('Data', {})
    
    # 初始化默认值
    primary_label = 'nonLabel'
    confidence = 1.0
    risk_level = 'none'
    description = "未检测出风险"
    risk_words = []
    
    # 提取结果信息
    if 'Result' in data and data['Result']:
        first_result = data['Result'][0]
        primary_label = first_result.get('Label', 'nonLabel')
        confidence = first_result.get('Confidence', 1.0) / 100.0  # 转换为0-1范围
        description = first_result.get('Description', "未检测出风险")
        risk_words = first_result.get('RiskWords', [])
    
    # 获取风险等级
    risk_level = data.get('RiskLevel', 'none')
    
    # 构建标准化响应
    return {
        'status': 200,
        'suggestion': risk_to_suggestion.get(risk_level, 'review'),
        'label': primary_label,
        'confidence': confidence,
        'details': {
            'api_response': response_dict,
            'risk_interpretation': description
        }
    }
#检测结果
def contentCheck(test_content):
    try:
        # 示例使用
        raw_result = text_moderation(test_content)
        
        if raw_result:

            # 转换为标准化格式
            normalized_result = normalize_response(raw_result)
            return normalized_result
        else:
            # 错误处理
            return {
                'status': 500,
                'suggestion': 'error',
                'label': 'api_error',
                'confidence': 0.0,
                'details': {
                    'error_type': '类型错误',
                    'error_message':'类型错误'
                }
            }
            
    except Exception as e:
            # 错误处理
            return {
                'status': 500,
                'suggestion': 'error',
                'label': 'api_error',
                'confidence': 0.0,
                'details': {
                    'error_type': '类型错误',
                    'error_message': str(e)
                }
            }

if __name__ == "__main__":
    content = '提供色情服务'
    #content = '好事将要发生'
    contentCheck_rs=contentCheck(content)
    print(contentCheck_rs)
    
